package com.itheima.Interceptor;

import com.itheima.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
@Slf4j
public class TokenInterceptor01 implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取url
        String url = request.getRequestURL().toString();
        // 判断是否包含 login
        if (url.contains("/login")){
            log.info("登录请求放行");
            return true;
        }
        // 获取token
        String token = request.getHeader("token");
        //判断token是否为空 或 token解析失败
        if (ObjectUtils.isEmpty(token)|| JwtUtils.parseJwt(token)==null){
            log.info("令牌为空,或令牌不正确");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 放行
        return true;
    }
}
